﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;

namespace netCoreStudy.Entities.Base
{
	public class PageList<T> : List<T> where T : class // 本身是一个集合 ，在集合 的基础上加了一些分页信息 
	{
		public int PageSize { get; private set; } //一页显示多少 数量
		public int PageIndex { get; private set; } // 当前页 加 private 避免 值在 类型 外被设置 

		public int TotalCount { get; private set; } //总数量
		public int TotalPages { get; private set; } //总共 有几页


		//构造函数 
		public PageList(List<T> items, int totalCount, int pageIndex, int pageSize)
		{
			TotalCount = totalCount;
			PageSize = pageSize;
			PageIndex = pageIndex;
			TotalPages = (int) Math.Ceiling(totalCount / (double) pageSize);
			AddRange(items);
		}


		public static async Task<PageList<T>> CreateAsync(IQueryable<T> source, int pageIndex,
			int pageSize)
		{
			var count = await source.CountAsync();
			var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
			return new PageList<T>(items, count, pageIndex, pageSize);
		}

		/// <summary>
		/// 将 pageList 转换 成 pageList
		/// <param name="pageList"></param>
		/// <param name="mapper"></param>
		/// <returns></returns>
		/// </summary>
		public static ResMsg<PageRes<TDto>> ToPageData<TDto>(PageList<T> pageList, IMapper mapper)
		{
			List<TDto> dtos =
				mapper.Map<List<TDto>>(pageList);
			ResMsg<PageRes<TDto>> resMsg = new ResMsg<PageRes<TDto>>(
				new PageRes<TDto>(
					pageList.PageIndex,
					pageList.PageSize,
					pageList.TotalCount,
					dtos
				));
			return resMsg;
		}
	}
}